package com.gy.zpchat.ui.chat.room.adapter;

import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

import im.zego.zim.entity.ZIMUserInfo;
import com.gy.zpchat.R;

public class RoomMemberListAdapter extends RecyclerView.Adapter {

    public List<ZIMUserInfo> userInfoList = new ArrayList<>();

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_group_member_selected, parent, false);
        return new RoomMemberListAdapter.RoomMemberViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        final RoomMemberListAdapter.RoomMemberViewHolder roomMemberViewHolder = (RoomMemberListAdapter.RoomMemberViewHolder) holder;

        ZIMUserInfo userInfo = userInfoList.get(position);
        roomMemberViewHolder.setRoomMemberInfo(userInfo);
    }

    @Override
    public int getItemCount() {
        return userInfoList.size();
    }

    public void addAll(List<ZIMUserInfo> infoList) {
        if (infoList != null) {
            userInfoList.addAll(infoList);
            notifyDataSetChanged();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void deleteAll(List<ZIMUserInfo> infoList) {
        if (infoList != null) {
            for (ZIMUserInfo info : infoList) {
                userInfoList.removeIf(e -> e.userID.equals(info.userID));
            }
            notifyDataSetChanged();
        }
    }

    class RoomMemberViewHolder extends RecyclerView.ViewHolder {

        TextView groupMemberNameTextView;

        public RoomMemberViewHolder(@NonNull View itemView) {
            super(itemView);
            groupMemberNameTextView = itemView.findViewById(R.id.group_member_name);
            View view = itemView.findViewById(R.id.group_member_selected);
            view.setVisibility(View.GONE);
        }

        public void setRoomMemberInfo(ZIMUserInfo info) {
            String name = info.userName;
            if (info.userName != null && !info.userName.equals("")) {
                name = info.userName;
            } else if (info.userID != null) {
                name = info.userID;
            }
            groupMemberNameTextView.setText(name);
        }
    }
}
